<?php
namespace Home\Controller;

class StaffController extends CommonController {
     
/*     public function index(){
        if (isset($_SESSION['username'])){
            $this->display();
        }else{
            header("location: ". __ROOT__."/index.php/login");
        }
    } */
    //查询所有员工信息
    public function select(){
        $limit=I('limit');
        $start=I('start');
        $pagesize=I('page');
    
        $staff = M('staff');
        $user = M('user');
        $dept = M('dept');
    
    
    
        if ('' !==I('id')){         //判断id是否存在 此处id是dept表的id对应staff表的department字段
            $department = I('id');
            $list = $staff->where('department='.$department)->limit($start,$limit)->select();
            $count = $staff->where('department='.$department)->count();
        }else {
            $count = $staff->count();
            $list = $staff->limit($start,$limit)->select();
        }
        foreach ($list as $k=>$v){
            $uid = $list[$k]['uid'];
            $department = $list[$k]['department'];
    
            $userlist = $user->field('username,password')->where('id='.$uid)->find();
            $list[$k]['username'] = $userlist['username'];
            $list[$k]['password'] = $userlist['password'];
            $deptlist = $dept->field('name')->where('id='.$department)->find();
            $list[$k]['deptname'] = $deptlist['name'];
        }
        //  var_dump($list[0]['etime']);
        //  var_dump(date('Y-m-d',null));
        //  die;
        foreach($list as $k=>$v){
    
            $list[$k]['birthday'] = $v['birthday']?date('Y-m-d',$v['birthday']):null;
            $list[$k]['stime'] = $v['stime']?date('Y-m-d',$v['stime']):null;
            $list[$k]['etime'] = $v['etime']?date('Y-m-d',$v['etime']):null;
            $list[$k]['rtime'] = $v['rtime']?date('Y-m-d',$v['rtime']):null;
            // var_dump($list);die;
        }
        //var_dump($list);die;
        //$data['birthday'] = date('d/m/Y',$data['birthday']);
        $data['total'] = $count;
        $data['data']=$list;
        $this->ajaxReturn($data);
    }
    
    //查询登录用户信息
    public function find(){
        /*       $limit=$_GET['limit'];
         $start=$_GET['start'];
         $pagesize=$_GET['page']; */
    
        $staff = M('staff');
        //         $count = $staff->count();
        $uid = $_SESSION['id'];
        //         $data['total'] = $count;
    
        $arr = $staff->field('id')->where("uid=$uid")->find();
        //var_dump($id);die;
        $id = $arr['id'];
        $list = $staff->find($id);
        //var_dump($list);die;
        //  var_dump($list[0]['etime']);
        //  var_dump(date('Y-m-d',null));
        //  die;
    
    
        $list['birthday'] = $list['birthday']?date('Y-m-d',$list['birthday']):null;
        $list['stime'] = $list['stime']?date('Y-m-d',$list['stime']):null;
        $list['etime'] = $list['etime']?date('Y-m-d',$list['etime']):null;
        $list['rtime'] = $list['rtime']?date('Y-m-d',$list['rtime']):null;
        // var_dump($list);die;
    
        //var_dump($list);die;
        //$data['birthday'] = date('d/m/Y',$data['birthday']);
        $data['data']=$list;
        $this->ajaxReturn($data);
    }
    
    
public function uploadPhoto(){
        $exts      =     array('jpg', 'gif', 'png', 'jpeg');// 设置附件上传类型
        $rootPath  =      './Public'; // 设置附件上传根目录
        $savePath  =      '/images/'; // 设置附件上传（子）目录
    
        $msg = '上传图片成功';
        $data = upload($exts, $rootPath, $savePath, $msg);
     //   if ($data['success']){}
        $this->ajaxReturn($data);
    }
    
    //单个添加员工信息
    public function add(){

        $user = D('user');
        
        $staff = D('staff');
        
        $data['photo'] = I('photo')?I('photo'):'/images/2016-04-07/5706251eb2d88.png';
       // var_dump($data['photo']);exit();
        $data['name'] = I('name');
        $data['ename'] = I('ename');
        $data['age'] = I('age');
        $data['sex'] = I('sex');
        $data['address'] = I('address');
        $data['department'] = I('department')?I('department'):15;
        $data['stime'] = strtotime(I('stime'));
        $data['sid'] = I('sid');
        $data['tel'] = I('tel');
        $data['email'] = I('email');
        $data['area'] = I('area');
        $data['position'] = I('position');
        $data['birthday'] = strtotime(I('birthday'));       
        $data['rtime'] = strtotime(I('rtime'));
        $data['etime'] = strtotime(I('etime'));
       
        //$data['photo'] = $this->_photo;
        //echo  $data['photo'];exit();
        //var_dump( $_FILES);exit();
        
        if (!$staff->create()){
            
            // 如果创建失败 表示验证没有通过 输出错误提示信息
            $result['success'] = false;
            $result['msg'] = $staff->getError();
            exit($this->ajaxReturn($result));
        }else{

            $udata['username'] = $data['ename'];
            $udata['password'] = '123456';
            $id = $user->add($udata);

            $data['uid'] = $id;
           
            if($staff->add($data)){
			$result['success']=true;
			$result['msg']='保存成功';
		}else{
			$result['success']=false;
			$result['msg']='保存失败';
		}
		echo $this->ajaxReturn($result);
        }       
    }
    
    //下载员工信息模板
    public function downloadExcel(){
        //Excel表格式,这里简略写了8列
        $letter = array('A','B','C','D','E','F','G','H','I','J','K','L','M','N','O');
        //表头数组
        $tableheader = array('姓名','英文名','性别','年龄','地址','部门','生日','工号','电话','邮箱','户籍','入职时间','离职时间','职位','转正时间');
        //表格数组
        $data = array(
            array('小王','xiaowang','男','20','那美克星铁岭村18号','外贸部','1988-04-06','工号','电话','邮箱','安徽','2015-04-06','','XX员工','2015-06-06'),
            array('小李','xiaoli','男','20','鸟不拉屎星火影村22弄22号','采购部','1988-05-06','工号','电话','邮箱','北京','2015-05-06','','XX经理','2015-07-06'),
            array('小张','xiaozhang','女','20','贝吉塔星赛亚村19幢2号','销售部','1988-03-06','工号','电话','邮箱','上海','2015-02-06','2016-04-06','XX主管','2015-04-06'),
            array('小赵','xiaozhao','女','20','地球村魔都南翔镇88号','技术部','1988-02-06','工号','电话','邮箱','苏州','2015-03-06','2016-04-06','XX总监','2015-04-06')
        );
        downloadExc($letter,$tableheader,$data);
    }
    
    //批量上传员工信息表
    public function uploadExcel(){
       $exts = array('xls');// 设置附件上传类型
       $rootPath  =      './Public'; // 设置附件上传根目录
       $savePath  =      '/Excel/'; // 设置附件上传（子）目录
       $msg = '上传Excel成功';
       $data = upload($exts, $rootPath, $savePath, $msg);
       $this->ajaxReturn($data);
    }
        
        
    //批量添加员工信息到数据库
    public function addAll(){
        
        $staff = D('staff');
        $user = D('user');
        $path = I('path');
        header("Content-type: text/html; charset=utf-8");
        import('Vendor.PHPExcel.PHPExcel','','.php');//导入类库
        import('Vendor.PHPExcel.PHPExcel.IOFactory','','.php');//导入类库
        import('Vendor.PHPExcel.PHPExcel.Reader.Excel2003','','.php');//导入类库


        $uploadfile='./Public/'.$path;//Excel文件的路径
        
        $objReader = \PHPExcel_IOFactory::createReader('Excel5');/*Excel5 for 2003 excel2007 for 2007*/
       // $objReader = \PHPExcel_IOFactory::createReaderForFile($filename);
        
        $objPHPExcel = $objReader->load($uploadfile); //读取Excel表格的信息
        
 /*        $sheet = $objPHPExcel->getSheet(0);//获得sheet1
        //var_dump($sheet);exit();
        $highestRow = $sheet->getHighestRow(); // 取得总行数
        $highestColumn = $sheet->getHighestColumn(); // 取得总列数 */
        
        
        //$objPHPExcel = new \PHPExcel();//类库没有用命名空间时 加 \  否则会调用当前命名空间
        
        $objWorksheet = $objPHPExcel->getActiveSheet();
        $highestRow = $objWorksheet->getHighestRow();   // 取得总行数
        $highestColumn = $objWorksheet->getHighestColumn();
        $highestColumnIndex = \PHPExcel_Cell::columnIndexFromString($highestColumn);//总列数
        
        for ($row = 2;$row <= $highestRow;$row++)         {
            $strs=array();
            //注意highestColumnIndex的列数索引从0开始
            for ($col = 0;$col < $highestColumnIndex;$col++)            {
                
                $strs[$col] =$objWorksheet->getCellByColumnAndRow($col, $row)->getValue();
                if(!$strs[0]){break 2;}
            }
           // var_dump($strs);exit();
            
/*             if (!$staff->create()){
            
                // 如果创建失败 表示验证没有通过 输出错误提示信息
                $result['success'] = false;
                $result['msg'] = $staff->getError();
                exit($this->ajaxReturn($result));
            }else{} */

        
            $data['photo'] = '/images/2016-04-07/5706251eb2d88.png';
            // var_dump($data['photo']);exit();
            $data['name'] = $strs[0];
            $data['ename'] = $strs[1];
            $data['age'] = $strs[3];
            $data['sex'] = $strs[2]=='男'?1:0;
            $data['address'] = $strs[4];
            $data['department'] = $strs[5];
            $data['stime'] = strtotime($strs[11]);
            $data['sid'] = $strs[7];
            $data['tel'] = $strs[8];
            $data['email'] = $strs[9];
            $data['area'] = $strs[10];
            $data['position'] = $strs[13];
            $data['birthday'] = strtotime($strs[6]);
            $data['etime'] = $strs[12];
            $data['rtime'] = $strs[14];
            
            $udata['username'] = $strs[1];
            $udata['password'] = '123456';
            
            
    /*   $sql = "DROP TRIGGER IF EXISTS `insertuser`;
             DELIMITER ;;
             CREATE TRIGGER `insertstaff` AFTER INSERT ON `tbl_user` FOR EACH ROW insert into tbl_staff  values(\'$data['name']\',\'$data['ename']\',\'$data['sex']\',\'$data['age']\',\'$data['address']\',
                \'$data['department']\',\'$data['birthday']\',\'$data['sid']\',\'$data['tel']\',\'$data['email']\',\'$data['area']\',
                    \'$data['stime']\',\'$data['etime']\',\'$data['position']\',\'$data['rtime']\',\'$data['uid']\',\'$data['isdelete']\',\'$data['photo']\',)";            
             */
            
             $user->startTrans();
            if($data['uid'] = $user->add($udata)){
                if($staff->add($data)){
                    $user->commit();
                    $result['success']=true;
                    $result['msg']='保存成功';
                
                }else{
                    $user->rollback();
                    $result['success']=false;
                    $result['msg']='保存失败';  
                     $this->ajaxReturn($result);
                }
            }   
        
//             $data['uid'] = $id;
            
           
             
        }
         $this->ajaxReturn($result);              
                
    }
       
    
    //删除选中的数据
    public function delete(){
        $data=I('data');
        $staff = D('staff');
        $map['id']=array('in',$data);
        //echo $post;
        if($staff->where($map)->delete()>0){
            $result['success']=true;
			$result['msg']='删除成功';
        }else{
            $result['success']=false;
			$result['msg']='删除失败';
        }

        $this->ajaxReturn($result);
    }

    //更新数据操作
    public function update(){
        $staff = D('staff');
        $data=I('post.'); 

        if(!$data['id']){
            $uid = $_SESSION['id'];
            $arr = $staff->field('id')->where("uid=$uid")->find();
            $data['id'] = $arr['id'];

        }
        

        $data['birthday'] = strtotime($data['birthday']);//把时间转换成时间戳存入数据库
        $data['stime'] = strtotime($data['stime']);
        $data['etime'] = strtotime($data['etime']);
        $data['rtime'] = strtotime($data['rtime']);
       
        //$datas['photo']=I('photo');
         
        if($staff->where("id=".$data['id'])->save($data)!==false){
            $result['data'] = $data;
            $result['success']=true;//返回修改后的状态
			$result['msg']='修改成功';//状态信息
        }else{
            $result['success']=false;
			$result['msg']='修改失败';
        }
        $this->ajaxReturn($result);
    }
}